/*
 * @Author: llk
 * @Date: 2022-03-31 22:56:45
 * @LastEditTime: 2022-05-24 19:10:50
 * @LastEditors: qianduanxuyaochendian lxy_01@outlook.com
 * @Description: 入口文件
 * @FilePath: \job\server\server.js
 */
// 引入express框架
const express = require("express")
// 引入Node.js中的http模块
const http = require("http")
// 引入数据库配置文件

// 引入请求体解析工具
const bodyParser = require("body-parser")
// 引入验证token的工具
// const passport = require('passport');
const { signkey } = require("./config/token")
const { expressjwt } = require("express-jwt")

// 引入跨域处理插件
const cors = require("cors")

//实例化app
const app = express()
app.use(cors())

// 使用body-parser中间件
app.use(
  bodyParser.urlencoded({
    extended: false,
  })
)
app.use(bodyParser.json())

// 初始化passport
// app.use(passport.initialize());
// require('./config/passport')(passport)

// 引入并使用请求封装的响应格式中间件
const { reply_success, reply_error } = require("./config/mid_reply")
app.use(reply_success)
app.use(reply_error)
const { ERROR_MSG } = require("./config/global")

const path = require("path")
app.use("/static", express.static(path.join(__dirname, "static")))

// token验证
app.use(
  expressjwt({
    secret: signkey,
    algorithms: ["HS256"],
  }).unless({
    path: [
      "/user/register",
      "/user/login",
      "/student/uploadPDF",
      "/company/search",
      "/company/getJobList",
      "/company/getResumeList",
      "/company/sendEmail",
    ], //设置白名单,除了配置的地址其余地址均需要验证
  })
)

// 引入路由文件
const userRouter = require("./router/userRouter")
const meetingRouter = require("./router/meetingRouter")
const companyRouter = require("./router/companyRouter")
const studentRouter = require("./router/studentRouter.js")
const jobRouter = require("./router/jobRouter.js")
const { socketFun } = require("./config/socket")

// 中间件使用路由
app.use("/user", userRouter)
app.use("/meeting", meetingRouter)
app.use("/company", companyRouter)
app.use("/student", studentRouter)
app.use("/job", jobRouter)
// 创建一个服务器
const server = http.createServer(app)

// 引入socket相关业务功能
socketFun(server)

// 错误处理中间件
app.use(function (err, req, res, next) {
  console.log("err", err)
  if (err.name === "UnauthorizedError") {
    res.reply_error(ERROR_MSG.UNAUTHORIZED_ACCESS, "TOKEN验证失败")
  } else {
    res.reply_error(ERROR_MSG.UNKNOWN_ERROR, "未知错误")
  }
})

// 定义端口号
const port = process.env.PORT || 5000

// 开启服务
server.listen(port, () => {
  console.log(`server running at http://127.0.0.1:${port}`)
})
